import {useState, useEffect, useRef} from 'react';
import {useNavigate} from 'react-router-dom';
import {Button, message} from "antd";
import dayjs from 'dayjs';
import {PlusOutlined} from '@ant-design/icons';
import PageTable from '@/components/PageTable.tsx';
import {findDicNameForDicCode, getDicOnCode} from '@/utils/dicAll.ts'
import {downloadFile} from '@/utils/index.ts'
import DynamicSearchForm from '@/components/DynamicSearchForm/index.tsx'
import PageActionBar from "@/components/PageActionBar.tsx"
import {exportProduct, queryAllCompany, updateProductStatus} from "@/axios/apis.ts"

const ProductLibraryList = () => {
    const navigate = useNavigate()
    const [searchFields, setSearchFields] = useState({
        search: [],
        expand: []
    })
    const [searchForm, setSearchForm] = useState({});
    const tableRef = useRef(null);
    const formRef = useRef(null);
    const [selectedRows, setSelectedRows] = useState<Array<object>>([]);
    const fields = {
        search: [
            {
                type: 'input',
                name: 'productCode',
                label: '产品编码',
                placeholder: '请输入',
            },
            {
                type: 'input',
                name: 'productName',
                label: '产品名称',
                placeholder: '请输入',
            },
            {
                type: 'select',
                name: 'companyCode',
                label: '保险公司',
                placeholder: '请选择',
                options: [],
                fieldNames: {
                    label: 'name',
                    value: 'companyCode'
                },
            },
        ],
        expand: [
            {
                type: 'select',
                name: 'companyCode',
                label: '状态',
                placeholder: '请选择',
                options: [],
            },
            {
                type: 'rangePicker',
                name: 'createTime',
                label: '修改时间'
            },
            {
                type: 'input',
                name: 'createUserName',
                label: '创建人',
                placeholder: '请输入',
            },
            // {
            //     type: 'custom',
            //     name: 'customField',
            //     label: '自定义字段',
            //     render: () => <Input placeholder="自定义渲染" />
            // }
        ]
    }
    const columns = [
        {
            title: "序号",
            dataIndex: "index",
            key: "index",
            render: (_1, _2, index) => <>{index + 1}</>,
            width: 50
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div className="table-options">
                    <span className="operation_style" onClick={() => {
                        const params = new URLSearchParams();
                        params.append('productId', record.id);
                        params.append('type', 'details');
                        params.append('insuranceCode', record.insuranceCode);
                        navigate(`/ProductionAdd?${params.toString()}`
                        )
                    }}>明细</span>
                </div>
            ),
            width: 100
        },
        {
            title: "产品编码",
            dataIndex: "productCode",
            key: "productCode",
        },
        {
            title: "产品名称",
            dataIndex: "productName",
            key: "productName",
        },
        {
            title: "保险公司",
            dataIndex: "insuranceName",
            key: "insuranceName",
        },
        {
            title: "产品状态",
            dataIndex: "status",
            key: "status",
            render: (value, record) => (
                <div>
                    <Button color={value === '3' ? 'danger' : 'cyan'} variant="link">
                        {findDicNameForDicCode('PRODUCT.STATUS', value)}
                    </Button>
                    <span>{Number(record.hotProduct) ? '热销' : ''}</span>
                    <span>{Number(record.presenterRisk) ? '赠险' : ''}</span>
                    <span>{Number(record.recommend) ? '推荐' : ''}</span>
                </div>
            ),
        }, {
            title: "修改时间",
            dataIndex: "updateTime",
            key: "updateTime",
        }, {
            title: "创建人",
            dataIndex: "createUserName",
            key: "createUserName",
        }, {
            title: "创建时间",
            dataIndex: "createTime",
            key: "createTime",
        }
    ];
    const handleSearch = (values: any) => {
        if (values.createTime?.length) {
            values.createTimeBegin = dayjs(values.createTime[0]).format('YYYY-MM-DD')
            values.createTimeEnd = dayjs(values.createTime[1]).format('YYYY-MM-DD')
            delete values.createTime
        }
        if (values.companyOrgCode?.length) {
            values.companyOrgCode = values.companyOrgCode[values.companyOrgCode.length - 1]
        }
        setSearchForm(values)
        tableRef?.current?.fetchData({}, values)
    }
    // 多选数组
    const multipleChange = (_: Array<string>, lists: Array<object>) => {
        setSelectedRows(lists)
    }
    useEffect(() => {
        queryAllCompany().then(res => {
            if (+res.code === 200) {
                fields.search[2].options = res.data
                setSearchFields(fields)
            }
        })
        fields.expand[0].options = getDicOnCode("PRODUCT.STATUS")
    }, [])
    // 上下架
    const upperAndLowerShelves = (status: string) => {
        if (!selectedRows || !selectedRows.length) {
            return message.error("请选择产品")
        }
        let flag = selectedRows.every(item => item.status !== status)
        if (!flag) {
            return message.error(status === "1"
                ? "已是上架状态，不能重复操作"
                : status === "2"
                    ? "已是不可投保状态，不能重复操作"
                    : "已是下架状态，不能重复操作")
        }
        updateProductStatus({
            id: selectedRows.map(ite => ite.id),
            status,
        }).then(res => {
            if (+res.code === 200) {
                message.success("操作成功")
                tableRef?.current?.fetchData({}, searchForm)
                tableRef?.current?.clearSelection()
            }
        })
    }
    const btnList = [
        {
            name: '新增保险产品',
            type: 'primary',
            icon: <PlusOutlined />,
            onClick: () => {
                navigate('/ProductionAdd')
            }
        },
        {
            name: '导出列表',
            onClick: () => {
                exportProduct({}).then(res => {
                    downloadFile(res)
                })
            }
        },
        {
            name: '上架',
            type: 'primary',
            onClick: () => upperAndLowerShelves('1')
        },
        {
            name: '下架',
            type: 'primary',
            onClick: () => upperAndLowerShelves('3')
        }
    ]
    return (
        <>
            <DynamicSearchForm fields={searchFields} onSearch={handleSearch} ref={formRef} />
            <PageActionBar btnList={btnList} />
            <PageTable
                columns={columns}
                reqestUrl="queryProductLibraryList"
                searchForm={searchForm}
                ref={tableRef}
                multiple={true}
                multipleChange={multipleChange}
            />
        </>
    );
};

export default ProductLibraryList;